<template>
    <div >
    
    
    <div class="imgLoad">
     <input type="file" class="updata" accept="image/*" style='display:none' @change="onFileChange" ref="updata"
    />
    <img :src="avatar" alt="" v-if='avatar'>
    <img src="@/assets/logo.png" alt="" v-else>
    <!-- <img :src="avatar ? avatar : baseImg" alt="" class="img" /> -->
    </div>
   <el-button @click="chooseImg" type='primary'>选择图片</el-button>
   <el-button type='success' @click="uploadFn">上传图片</el-button>
    </div>
     
</template>


<script>
import {updateAvatar} from '@/api/http'
  export default {
    data() {
      return {
        avatar:'',
        baseImg:'@/assets/logo.png'
      };
    },
    methods: {
     chooseImg () {
        this.$refs.updata.click()
     },
    onFileChange(e){
    const files = e.target.files
    if(files.length === 0){

}else{
    console.log(files[0])
    const fr = new FileReader()
    fr.readAsDataURL(files[0])
    fr.onload =(e) => {
        this.avatar=e.target.result
        console.log(this.avatar)
    }
}
    },
  async  uploadFn(){
    console.log('上传')
    const {data:res} = await updateAvatar(this.avatar)
    console.log(res)
    if(res.code === 0){
        this.$message.success('上传成功')
      this.$store.dispatch('getuserinfo')
    } else{this.$message.error('上传失败')}
     },

    },
    created() {
         this.chooseImg ()
    },
  }
</script>
<style lang='less' scoped>
.imgLoad{
    width: 200px;
    height: 300px;
    background-color: #eee;
    img{
        width: 100%;
        height: 100%;
    }
}
</style>